package component.fulltextsearch.index;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.apache.lucene.index.Term;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.Filter;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.QueryWrapperFilter;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.BooleanClause.Occur;

import component.fulltextsearch.constant.SearchConstant;

/**
 * 查询过滤器生成器
 *
 */
public abstract class FilterBuilder {
	
	/**
	 * 构建带公共权限的权限过滤器.
	 * @param userArray
	 * @param roleArray
	 * @return
	 */
	public static Filter builderRightFilterIncludePub(String[] userArray, String[] roleArray) { 
		if (userArray == null) {
			userArray = new String[] {};
		} 		
		if (roleArray == null) {
			roleArray = new String[] {};
		}
		List userList = new ArrayList(Arrays.asList(userArray));
		List roleList = new ArrayList(Arrays.asList(roleArray));
		userList.add(SearchConstant.RIGHT_PUB);
		roleList.add(SearchConstant.RIGHT_PUB);
		return builderRightFilter(userList,roleList);
	}
	
	/**
	 * 构建权限过滤器
	 * 构建条件的结果：(用户1 or 用户2 or ...) or (角色1 or 角色2 or ...)
	 * @param userArray
	 * @param roleArray
	 * @return
	 */
	public static Filter builderRightFilter(List userArray, List roleArray) { 
		BooleanQuery booleanQuery = new BooleanQuery();
		if (userArray != null && userArray.size() > 0) {
			BooleanQuery userBooleanQuery = new BooleanQuery();
			for (int i = 0; i < userArray.size(); i ++) {
				Query userQuery = new TermQuery(new Term(SearchConstant.NAME_RIGHTUSERS,(String) userArray.get(i)));
				userBooleanQuery.add(userQuery,Occur.SHOULD);
			}
			booleanQuery.add(userBooleanQuery,Occur.SHOULD);
		}
		if (roleArray != null && roleArray.size() > 0) {
			BooleanQuery roleBooleanQuery = new BooleanQuery();
			for (int i = 0; i < roleArray.size(); i ++) {
				Query roleQuery = new TermQuery(new Term(SearchConstant.NAME_RIGHTROLES,(String) roleArray.get(i)));
				roleBooleanQuery.add(roleQuery,Occur.SHOULD);
			}
			booleanQuery.add(roleBooleanQuery,Occur.SHOULD);
		}
		return new QueryWrapperFilter(booleanQuery);
	}
	
	/**
	 * 构建权限过滤器.
	 * @param userArray
	 * @param roleArray
	 * @return
	 */
	public static Filter builderRightFilter(String[] userArray, String[] roleArray) { 
		return  builderRightFilter(Arrays.asList(userArray),Arrays.asList(roleArray));
	}
}